package com.weimengchao.core.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "LogFilter", urlPatterns = "/*")
@Slf4j
@Component
public class LogFilter implements Filter {

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        final HttpServletRequest reqs = (HttpServletRequest) req;
        String requestId = reqs.getHeader(RequestIdMdcUtil.REQUEST_ID);
        if (StrUtil.isBlank(requestId)) {
            requestId = RequestIdMdcUtil.getRequestId();
        }

        MDC.put(RequestIdMdcUtil.REQUEST_ID, requestId);
        log.info("LogFilter触发request_id:{}", MDC.get(RequestIdMdcUtil.REQUEST_ID));
        try {
            chain.doFilter(req, res);
        } finally {
            MDC.remove(RequestIdMdcUtil.REQUEST_ID);
        }
    }

    @Override
    public void init(final FilterConfig filterConfig) {
        log.info("LogFilter初始化");
    }

    @Override
    public void destroy() {
        MDC.remove(RequestIdMdcUtil.REQUEST_ID);
    }
}